﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using PhotoGallery.Core.Business;
using PhotoGallery.Infrastructure.Helpers;
using System.Web.Script.Serialization;

namespace PhotoGallery.Modules.Authority.Controllers
{
    public class RoleController : Controller
    {
        #region  Field & Property

        #endregion


        #region Constructor

        public RoleController()
        {

        }

        #endregion

        #region 操作

        /// <summary>
        /// Index
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityFilterAttribute(Order = 1)]
        public ActionResult Index(int? index)
        {
            if (TempData["HintMessage"] != null)
            {
                ViewData["HintMessage"] = TempData["HintMessage"];
            }
            RoleIndexModel model = new RoleIndexModel(Role.GetAllRoles(), index, Operation.Search(new OperationSearch() { Status = (int?)0 }));

            //model.Current.Operations = Operation.Find(model.Current, 0);

            return View(model);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityFilterAttribute(Order = 1)]
        public ActionResult Delete(int? id)
        {

            Role role = null;
            if (id == null || !id.HasValue || (role = Role.Load(id.Value)) == null)
            {
                TempData["HintMessage"] = new HintMessage { Content = string.Format("角色({0})不存在，请检查", role.Name) };
                return RedirectToAction("Index");
            }
            role.DeleteOnSave();
            role.Save();
            TempData["HintMessage"] = new HintMessage { Content = string.Format("角色({0})删除成功", role.Name) };
            return RedirectToAction("Index");
        }

        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        public ActionResult Add()
        {

            return View();
        }


        /// <summary>
        /// 创建
        /// </summary>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityFilterAttribute(Order = 1)]
        public ActionResult Create(Role model)
        {
            if (model == null)
                throw new ArgumentNullException("请检查输入！！");
            model.Save();
            TempData["HintMessage"] = new HintMessage { Content = string.Format("角色({0})添加成功", model.Name) };
            return RedirectToAction("Index");
        }


        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityFilterAttribute(Order = 1)]
        public ActionResult Edit(int? id)
        {
            Role model = null;
            if (id == null || !id.HasValue || (model = Role.Load(id.Value)) == null)
            {
                TempData["HintMessage"] = new HintMessage { Content = "角色不存在，请检查" };
                return RedirectToAction("Index");
            }
            return View(model);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityFilterAttribute(Order = 1)]
        public ActionResult Update(Role model)
        {
            Role orgin = null;
            if (model == null || (orgin = Role.Load(model.Id)) == null)
            {
                TempData["HintMessage"] = new HintMessage { Content = string.Format("角色({0})不存在，请检查") };
                return RedirectToAction("Index");
            }

            orgin.Name = model.Name;
            orgin.Status = model.Status;
            orgin.Description = model.Description;
            orgin.Save();

            TempData["HintMessage"] = new HintMessage { Content = string.Format("角色({0})更新成功!", model.Name) };
            return RedirectToAction("Index");
        }

        /// <summary>
        /// 保存 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
        [LoginFilterAttribute(Order = 0)]
        [SecurityJsonFilterAttribute(Order = 1)]
        public JsonResult Save(string operations, int? id)
        {

            if (operations == null || id == null || !id.HasValue)
            {
                return Json(new { success = false, message = "更新失败", status = "error" });
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            IList<int> operationids = serializer.Deserialize<IList<int>>(operations);

            Role role = Role.Load(id.Value);

            if (role == null)
            {
                return Json(new { success = false, message = "更新失败,请检查输入", status = "error" });
            }

            IList<Operation> existOperation = role.Operations;

            foreach (var n in operationids)
            {
                Operation operation = Operation.Load(n);
                if (operation == null)
                    continue;

                RoleOperation roleOperation = RoleOperation.Load(new RoleOperationKey() { RoleId = id.Value, OperationId = n });

                if (roleOperation == null)
                {
                    roleOperation = new RoleOperation();
                    roleOperation.Id = new RoleOperationKey() { OperationId = n, RoleId = id.Value };
                    //roleOperation.Status = 0;
                    roleOperation.Save();
                }
                else
                {
                    existOperation.Remove(operation);
                }
            }

            foreach (var d in existOperation)
            {
                RoleOperation roleOperation = RoleOperation.Load(new RoleOperationKey() { OperationId = d.Id, RoleId = id.Value });
                roleOperation.DeleteOnSave();
                roleOperation.Save();
            }

            return Json(new { success = true, message = "更新成功", status = "success" });
        }


        #endregion

        #region Json

        public JsonResult CheckRoleName(string name)
        {
            if (string.IsNullOrEmpty(name))
                return Json(new { success = false, message = "请检查输入是否正确！", status = "error" });
            Role role = Role.Find(name);
            if (role == null)
                return Json(new { success = true, message = "该角色名可以使用！", status = "success" });
            else
                return Json(new { success = false, message = "该名称不可使用，已经有相同的角色名！", status = "error" });
        }

        #endregion
    }
}
